using Microsoft.AspNetCore.Mvc;
using UniversalAdminSystem.Application.PermissionManagement.DTOs;
using UniversalAdminSystem.Application.PermissionManagement.Interfaces;
using UniversalAdminSystem.Api.Attributes;
using UniversalAdminSystem.Application.Common.Results;

namespace UniversalAdminSystem.Api.Controllers;

/// <summary>
/// 角色管理控制器
/// 提供角色的创建、查询、权限分配等操作
/// </summary>
[ApiController]
[Route("api/roles")]
public class RoleController : ControllerBase
{
    private readonly IRoleManagementAppService _roleManagementAppService;
    private readonly IPermissionManagementAppService _permissionAppService;

    public RoleController(
        IRoleManagementAppService roleManagementAppService,
        IPermissionManagementAppService permissionAppService)
    {
        _roleManagementAppService = roleManagementAppService;
        _permissionAppService = permissionAppService;
    }

    /// <summary>
    /// 获取所有角色列表
    /// </summary>
    [HttpGet]
    [RequirePermission("role:Read")]
    public async Task<IActionResult> GetAllRolesAsync()
    {
        try
        {
            var roles = await _roleManagementAppService.GetAllRolesAsync();
            return Ok(Result<IEnumerable<RoleDto>>.Success(roles));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<IEnumerable<RoleDto>>.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 根据ID获取角色
    /// </summary>
    [HttpGet("{roleId}")]
    [RequirePermission("role:Read")]
    public async Task<IActionResult> GetRoleByIdAsync(Guid roleId)
    {
        try
        {
            var role = await _roleManagementAppService.GetRoleByIdAsync(roleId);
            if (role == null)
            {
                return NotFound(Result<RoleDto>.Failure("角色不存在"));
            }
            return Ok(Result<RoleDto>.Success(role));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<RoleDto>.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 创建新角色
    /// </summary>
    [HttpPost]
    [RequirePermission("role:Create")]
    public async Task<IActionResult> CreateRoleAsync([FromBody] RoleCreateDto createDto)
    {
        try
        {
            var role = await _roleManagementAppService.CreateRoleAsync(createDto);
            return Ok(Result<RoleDto>.Success(role));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<RoleDto>.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 更新角色信息
    /// </summary>
    [HttpPut("{roleId}")]
    [RequirePermission("role:Update")]
    public async Task<IActionResult> UpdateRoleAsync(Guid roleId, [FromBody] RoleUpdateDto updateDto)
    {
        try
        {
            var role = await _roleManagementAppService.UpdateRoleAsync(roleId, updateDto);
            return Ok(Result<RoleDto>.Success(role));
        }
        catch (KeyNotFoundException)
        {
            return NotFound(Result<RoleDto>.Failure("角色不存在"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<RoleDto>.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 删除角色
    /// </summary>
    [HttpDelete("{roleId}")]
    [RequirePermission("role:Delete")]
    public async Task<IActionResult> DeleteRoleAsync(Guid roleId)
    {
        try
        {
            await _roleManagementAppService.DeleteRoleAsync(roleId);
            return Ok(Result.Success("角色删除成功"));
        }
        catch (KeyNotFoundException)
        {
            return NotFound(Result.Failure("角色不存在"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 为角色分配权限
    /// </summary>
    [HttpPost("{roleId}/permissions")]
    [RequirePermission("role:Update")]
    public async Task<IActionResult> AssignPermissionsToRoleAsync(
        Guid roleId, 
        [FromBody] List<string> permissionCodes)
    {
        try
        {
            // 将权限编码转换为权限ID（这里需要根据实际需求调整）
            
            foreach (var permissionCode in permissionCodes)
            {
                var assignDto = new AssignPermissionDto(permissionCode, roleId);
                await _permissionAppService.AssignPermissionToRoleAsync(assignDto);
            }
            return Ok(Result.Success("角色权限分配成功"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 为角色分配权限（使用权限ID）
    /// </summary>
    [HttpPost("{roleId}/permissions/ids")]
    [RequirePermission("role:Update")]
    public async Task<IActionResult> AssignPermissionsToRoleByIdsAsync(
        Guid roleId, 
        [FromBody] List<Guid> permissionIds)
    {
        try
        {
            await _roleManagementAppService.AssignPermissionsToRoleAsync(roleId, permissionIds);
            return Ok(Result.Success("角色权限分配成功"));
        }
        catch (KeyNotFoundException)
        {
            return NotFound(Result.Failure("角色不存在"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 移除角色的权限
    /// </summary>
    [HttpDelete("{roleId}/permissions")]
    [RequirePermission("role:Update")]
    public async Task<IActionResult> RemovePermissionsFromRoleAsync(
        Guid roleId, 
        [FromBody] List<Guid> permissionIds)
    {
        try
        {
            await _roleManagementAppService.RemovePermissionsFromRoleAsync(roleId, permissionIds);
            return Ok(Result.Success("角色权限移除成功"));
        }
        catch (KeyNotFoundException)
        {
            return NotFound(Result.Failure("角色不存在"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result.Failure(ex.Message));
        }
    }

    /// <summary>
    /// 获取角色的所有权限
    /// </summary>
    [HttpGet("{roleId}/permissions")]
    [RequirePermission("role:Read")]
    public async Task<IActionResult> GetRolePermissionsAsync(Guid roleId)
    {
        try
        {
            var permissions = await _roleManagementAppService.GetRolePermissionsAsync(roleId);
            return Ok(Result<IEnumerable<PermissionDto>>.Success(permissions));
        }
        catch (KeyNotFoundException)
        {
            return NotFound(Result<IEnumerable<PermissionDto>>.Failure("角色不存在"));
        }
        catch (Exception ex)
        {
            return BadRequest(Result<IEnumerable<PermissionDto>>.Failure(ex.Message));
        }
    }
} 